import Combine
import Kingfisher
import SwiftUI

/// 轮播图
struct AutoLoopCarouselView: View {
    let images: [String] // 本地或网络图片路径
    var height: CGFloat = 250
    private let timer: Publishers.Autoconnect<Timer.TimerPublisher> = Timer.publish(
        every: 3, on: .main, in: .common
    ).autoconnect()

    @State var currentIndex: Int = 1 // 初始显示第1张真实图

    var body: some View {
        let extendedImages = [images.last!] + images + [images.first!]

        ZStack(alignment: .topTrailing) {
            TabView(selection: $currentIndex) {
                ForEach(0 ..< extendedImages.count, id: \.self) { index in
                    KFImage.url(URL(string: extendedImages[index]), cacheKey: extendedImages[index])
                        .placeholder({
                            WebImageLoadingView()
                        })
                        .onFailureImage(.iconPlaceholderHeader)
                        .resizable()
                        .scaledToFill()
                        .tag(index)
                }
            }
            .tabViewStyle(.page(indexDisplayMode: .never))
            .frame(height: height)
            .onReceive(timer) { _ in
                withAnimation {
                    currentIndex += 1
                }
            }
            .onChange(of: currentIndex) { _, newValue in

                if newValue == extendedImages.count - 1 {
                    // 到达最后一个“假图”后无动画跳转回第1张
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                        currentIndex = 1
                    }
                }
                if newValue == 0 {
                    // 回到第一个“假图”后无动画跳转到最后一张
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                        currentIndex = extendedImages.count - 2
                    }
                }
            }
            // 页码
            Text("图片(\(currentPageIndex())/\(images.count))")
                .font(.alibabaPuHuiTi(size: 12.0, weight: .medium))
                .foregroundStyle(Color.fsFFFFFF)
                .padding(.horizontal, 8.0)
                .padding(.vertical, 4.0)
                .background(
                    Capsule()
                        .fill(Color.fs000000.opacity(0.4))
                )
                .padding(.top, safeTopPadding())
                .padding(.trailing, 12.0)
            
        }
    }

    private func currentPageIndex() -> Int {
        // 显示当前真实页码
        if images.isEmpty { return 0 }
        return ((currentIndex - 1) + images.count) % images.count + 1
    }

    private func safeTopPadding() -> CGFloat {
        if let top = UIApplication.shared.windows.first?.safeAreaInsets.top {
            return top + 8
        } else {
            return 14
        }
    }
}
